package com.cqut.forum.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cqut.forum.entity.Hotpost;
import com.cqut.forum.entity.Plate;
import com.cqut.forum.entity.Post;
import com.cqut.forum.entity.Theme;
import com.cqut.forum.entity.User;
import com.cqut.forum.lucene.LuceneIndex;
import com.cqut.forum.lucene.LuceneSearch;
import com.cqut.forum.service.IPlateService;
import com.cqut.forum.service.IPostService;
import com.cqut.forum.service.IThemeService;
import com.cqut.forum.service.IUserService;
import com.cqut.forum.util.ConfigProperties;
import com.cqut.forum.util.CookieHandler;
import com.cqut.forum.util.DESUtils;
import com.cqut.forum.util.DateUtil;
import com.cqut.forum.util.DefaultElements;
import com.cqut.forum.util.StringUtil;

@Controller
public class indexController {
	
	private IThemeService themeService;
	private IPlateService plateService;
	private IPostService  postService;
	private IUserService userService;
	
	public IThemeService getThemeService() {
		return themeService;
	}


	public void setThemeService(IThemeService themeService) {
		this.themeService = themeService;
	}


	public IPlateService getPlateService() {
		return plateService;
	}


	public void setPlateService(IPlateService plateService) {
		this.plateService = plateService;
	}


	public IPostService getPostService() {
		return postService;
	}

	public IUserService getUserService() {
		return userService;
	}


	public void setUserService(IUserService userService) {
		this.userService = userService;
	}


	public void setPostService(IPostService postService) {
		this.postService = postService;
	}


	/**
	* @author 刘强
	* @Title: indexView
	* @Description: 返回index页面
	* @return String
	* @date 2015年4月21日 下午4:31:38
	*/ 
	@RequestMapping(value="/index.do")
	public String index(HttpServletRequest request,
			HttpServletResponse response)throws Exception{		
		List<Theme> themes=themeService.list(Theme.class);
		for(Theme theme:themes){
			List<Plate> plates=plateService.getPlatesByTheme(theme.getId());
			theme.setPlates(plates);
		}
		List<Hotpost> hotposts_0 =postService.getHotPostByType(DefaultElements.ZERO, DefaultElements.SIX);
		List<Post> hotposts_1 =postService.getPostByHotpost(DefaultElements.ONE, DefaultElements.TEN);
		request.setAttribute("themes", themes);
		request.setAttribute("hotposts_0", hotposts_0);
		request.setAttribute("hotposts_1", hotposts_1);
		return "/home/index";
	}
	/**
	* @Title: plate
	* @Description: 返回plate列表页面 
	* @return String  
	* @author 刘强   
	* @date 2015-5-6 下午2:09:14
	*/ 
	@RequestMapping(value="/plate.do")
	public String plate(HttpServletRequest request,HttpServletResponse response){
		String plateId=request.getParameter("id");
		if(null==plateId||plateId.equals("")){
		}
		Plate plate=plateService.getPlateById(Long.parseLong(plateId));
		List<Hotpost> hotposts_0 =postService.getHotPostByType(DefaultElements.ZERO, DefaultElements.SIX);
		List<Post> hotposts_1 =postService.getPostByHotpost(DefaultElements.ONE, DefaultElements.TEN);
		List<Plate> plates=plateService.getPlateByPlateId(plate.getId());
		request.setAttribute("plate", plate);
		request.setAttribute("hotposts_0", hotposts_0);
		request.setAttribute("hotposts_1", hotposts_1);	
		request.setAttribute("plates", plates);
		return "home/postlist";
	}
	/**
	* @Title: plateDetail
	* @Description: 用于异步加载plate列表页面  
	* @return void  
	* @author 刘强   
	* @date 2015-5-6 下午2:09:05
	*/ 
	@RequestMapping(value="/plateDetail.do")
	public void plateDetail(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String plateId=request.getParameter("plateId");
		String page=request.getParameter("page");
		int pageSize=Integer.parseInt(ConfigProperties.get("postRowNumber"));
		List<Post> posts=postService.getPostByPlateId(Long.parseLong(plateId), Integer.parseInt(page),pageSize);
		int total=postService.getPostTotalByPlateId(Long.parseLong(plateId));
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", posts);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: sendPost
	* @Description: 发帖  
	* @return void  
	* @author 刘强   
	* @date 2015-5-6 下午2:08:29
	*/ 
	@RequestMapping(value="/sendPost.do")
	public void sendPost(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String plate=request.getParameter("plate");
		String content=request.getParameter("content");
		String title=request.getParameter("title");
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);
		Post post=new Post();
		post.setPlateId(Long.parseLong(plate));
		post.setUserId(user.getId());
		post.setUserName(user.getUserName());
		post.setName(title);
		post.setContent(content);
		post.setPostDate(DateUtil.getCurrentTimestamp());
		post.setUpdateDate(DateUtil.getCurrentTimestamp());
		post.setPageView((long) 0);
		post.setReplyNumber((long) 0);
		postService.save(post);
		this.writeXMLForPostId(post.getId());//将id写入xml文件
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
/////////////////////////////////////////////////////////////全文检索测试	
	
	private LuceneIndex luceneIndex;
	private LuceneSearch luceneSearch;
	@RequestMapping(value="/luceneindexV.do")
	public String luceneindexV(HttpServletRequest request,HttpServletResponse response){
		return "home/postindex";
	}
	@RequestMapping(value="/luceneIndex.do")
	public void luceneIndex(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
	    List<Post> posts=postService.getAll();
	    luceneIndex.addIndex(posts);
	    root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	    
	}
	/**
	* @Title: luceneSeach
	* @Description: 返回搜索结果页面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-9 上午2:10:21
	*/ 
	@RequestMapping(value="/luceneSeach.do")
    public String luceneSeach(HttpServletRequest request,HttpServletResponse response){
    	String target = null;
		try {
			target = new String(request.getParameter("target").getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} ;
    	List<Hotpost> hotposts_0 =postService.getHotPostByType(DefaultElements.ZERO, DefaultElements.SIX);
		List<Post> hotposts_1 =postService.getPostByHotpost(DefaultElements.ONE, DefaultElements.TEN);
		request.setAttribute("hotposts_0", hotposts_0);
		request.setAttribute("hotposts_1", hotposts_1);	
		request.setAttribute("target", target);
    	return "home/postsearch";
    }
	/**
	* @Title: luceneSeachJson
	* @Description: 分页加载搜索结果  
	* @return void  
	* @author 刘强   
	* @date 2015-5-9 上午2:10:26
	*/ 
	@RequestMapping(value="luceneSeachJson.do")
    public void luceneSeachJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String target = request.getParameter("target");
		String page=request.getParameter("page");
		int pageSize=Integer.parseInt(ConfigProperties.get("postRowNumber")); 
		luceneSearch.init();//初始化
    	List<String> searchReulst=luceneSearch.search(target,Integer.parseInt(page),pageSize);
    	List<Post> posts=new ArrayList<Post>();
    	for(String str:searchReulst){
    		Post post=postService.getPostById(Long.parseLong(str));
    		posts.add(post);
    	}
    	int total=luceneSearch.total(target);
    	int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
    	root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", posts);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

    }
	public LuceneIndex getLuceneIndex() {
		return luceneIndex;
	}


	public void setLuceneIndex(LuceneIndex luceneIndex) {
		this.luceneIndex = luceneIndex;
	}


	public LuceneSearch getLuceneSearch() {
		return luceneSearch;
	}


	public void setLuceneSearch(LuceneSearch luceneSearch) {
		this.luceneSearch = luceneSearch;
	}
	
	
	/**
	* @Title: writeXMLForPostId
	* @Description: 将postId写入xml文件  
	* @return void  
	* @author 刘强   
	* @date 2015-5-12 下午9:53:05
	*/ 
	private void writeXMLForPostId(Long postId){
        try {
            XMLWriter writer = null;// 声明写XML的对象
            SAXReader reader = new SAXReader();

            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");// 设置XML文件的编码格式

            String filePath = ConfigProperties.get("postidpath");
            File file = new File(filePath);
            if (file.exists()) {
                Document document = reader.read(file);// 读取XML文件
                Element root = document.getRootElement();// 得到根节点
                boolean bl = true;
                // 添加一个id节点
                Element id = root.addElement("id");
                id.setText(postId.toString());
                
                writer = new XMLWriter(new FileWriter(filePath), format);
                writer.write(document);
                writer.close();
            } else {
                // 新建xml文件并新增内容
                Document _document = DocumentHelper.createDocument();
                Element _root = _document.addElement("post");
                Element id = _root.addElement("id");
                id.setText(postId.toString());

                writer = new XMLWriter(new FileWriter(file), format);
                writer.write(_document);
                writer.close();
            }
            System.out.println("操作结束! ");
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
}
